package org.softcognito.webcontent.radiomaryja;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ContentImpl implements Content {

	@Override
	public List<CategoryDTO> getCategories(String url) throws IOException {
		Document doc = getWebContent(url);
		List<CategoryDTO> linksList = new ArrayList<CategoryDTO>();
		Elements elements = doc.getElementsByAttributeValue("id",
				"menu-item-279883");
		for (Element element : elements.select("a").not("li")) {
			linksList.add(new CategoryDTOImpl(element.attr("href").toString(),
					element.text().toString()));
		}
		return linksList;
	}

	@Override
	public List<ItemDTO> getCategoryContent(String url) throws IOException {
		Document doc = getWebContent(url);
		List<ItemDTO> articlesList = new ArrayList<ItemDTO>();
		Elements elements = doc.getElementsByAttributeValue("class", "entry");
		for (Element element : elements) {
			String title = "";
			if (element
					.getElementsByAttributeValue("class",
							"article-title article-title-noimage").text()
					.toString().length() == 0) {
				title = element
						.getElementsByAttributeValue("class",
								"article-title article-title-noimage").text()
						.toString();
			} else {
				title = element
						.getElementsByAttributeValue("class", "article-title")
						.text().toString();
			}
			articlesList.add(new ItemDTOImpl(element.getElementsByTag("a")
					.attr("href").toString(), title, element
					.getElementsByAttributeValue("class", "excerpt").text()
					.toString(), element
					.getElementsByAttributeValue("style",
							"width:100%; clear:both;").text().toString(),
					element.getElementsByAttributeValue("class", "date").text()
							.toString(), element.getElementsByTag("img")
							.attr("src").toString()));
		}
		return articlesList;
	}

	private Document getWebContent(String url) throws IOException {
		Document document = null;
		document = Jsoup.connect(url).header("Accept", "text/html")
				.header("Host", "Opera").get();

		return document;
	}

	@Override
	public ItemDetailDTO getItemContent(String url) throws IOException {
		Document doc = getWebContent(url);
		Elements elements = doc.getElementsByAttributeValue("id", "artykul");
		Element element = elements.get(0);
		ItemDetailDTO det = new ItemDetailDTOImpl(element.toString(), element
				.getElementsByTag("source").attr("src").toString());
		return det;
	}
}
